package com.lagou.edu.service.impl;

import com.alibaba.fastjson.JSON;
import com.lagou.edu.dao.CodeDao;
import com.lagou.edu.enums.CodeStatus;
import com.lagou.edu.pojo.LagouAuthCode;
import com.lagou.edu.service.CodeService;
import com.lagou.edu.service.EmailService;
import com.lagou.edu.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Author grung
 * @Date 2020/10/24 15:27
 * @Version 1.0
 */

@Slf4j
@Service
@Component
public class CodServiceImpl implements CodeService {

    @Autowired
    private CodeDao codeDao;


    @Reference
    private EmailService emailService;

    @Override
    public Result create(String email) {


        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 10000));

        //获取最新的验证码
        List<LagouAuthCode> lagouAuthCodeList = codeDao.findLagouAuthCodeByEmailOrderByExpiretimeDesc(email);
        if(!CollectionUtils.isEmpty(lagouAuthCodeList)){
            LagouAuthCode lagouAuthCode = lagouAuthCodeList.get(0);
            System.out.println(JSON.toJSON(lagouAuthCode));

            //验证码时间是否过期
            if(lagouAuthCode.getExpiretime().getTime() - System.currentTimeMillis() > 0){
                code = lagouAuthCode.getCode();
            }
        }


        Boolean sendEmailFlag = emailService.sendEmail(email, code);
        if (sendEmailFlag){
            LagouAuthCode lagouAuthCode = new LagouAuthCode();
            lagouAuthCode.setEmail(email);
            lagouAuthCode.setCode(code);
            lagouAuthCode.setCreatetime(new Date());

            Calendar nowTime = Calendar.getInstance();
            nowTime.add(Calendar.MINUTE,10);
            lagouAuthCode.setExpiretime(nowTime.getTime());
            codeDao.save(lagouAuthCode);
            return Result.ok(code);
        }


        return Result.error("验证码发送失败，请检查邮箱地址稍后再试");
    }

    @Override
    public Integer vaildate(String email, String code) {

        //获取最新的验证码
        List<LagouAuthCode> lagouAuthCodeList = codeDao.findLagouAuthCodeByEmailAndCodeOrderByExpiretimeDesc(email,code);
        if(CollectionUtils.isEmpty(lagouAuthCodeList)){
            log.error("验证码或邮箱不正确，请重新输入>>>{},{}",email,code);
            return CodeStatus.WRONG.getCode();
        }

        LagouAuthCode lagouAuthCode = lagouAuthCodeList.get(0);
        long nowTime = System.currentTimeMillis();
        if (lagouAuthCode.getExpiretime().getTime()-nowTime<0){
            log.info("验证码超时，请重新输入>>>{},{}",email,code);
            return CodeStatus.TIME_OUT.getCode();
        }


        return CodeStatus.RIGHT.getCode();
    }
}
